package fy.hr.dao;

import fy.config.FyConfig;
import fy.hr.bean.LeaveFormBean;
import fy.hr.constant.OA2HRConstant;
import fy.util.DBUtil;
import fy.util.MyUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import fy.util.MyUtil;
public class LeaveForm_Elimination_Dao
{
  private static Log log = LogFactory.getLog(LeaveForm_Elimination_Dao.class);
  private static final String UPDATE_TBM_LEAVEB = "update tbm_leaveb b set b.leavebeginday = ?, b.leavebegintime = ?, b.leaveendday = ?, b.leaveendtime = ?, b.leavesumhour = ?, b.leavenote = ? where b.pk_leave_b = ?";
  private String errorMsg;
  private LeaveFormBean leaveBean;
  private List<String> workDayArray;
  private List<String> holidayArray;
  private String startTime;
	private String endTime;
  public void setLeaveBean(LeaveFormBean leaveBean)
  {
    this.leaveBean = leaveBean;
  }
  
  public String getErrorMsg()
  {
    return this.errorMsg;
  }
  
  public boolean write(String accountID)
  {
	  

    boolean success = false;
    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;
    try
    {
      conn = DBUtil.connect(FyConfig.getEHR_DB_CONFIG());
      
      pst = conn
        .prepareStatement("select p.pk_psndoc, p.pk_deptdoc, p.pk_corp, t.pk_tbm_psndoc from bd_psndoc p left join tbm_psndoc t on t.pk_psndoc=p.pk_psndoc and ( t.dr is null or t.dr = '0') where to_date(t.enddate,'yyyy-mm-dd') > sysdate and p.psnclscope='0' and p.psncode=? and ( p.dr is null or p.dr = '0')");
      
      pst.setString(1, this.leaveBean.getMemberCode());
	
      rs = pst.executeQuery();
      if (rs.next())
      {
        String pk_psndoc = rs.getString(1);
        
        String pk_corp = rs.getString(3);
        String pk_tbm_psndoc = rs.getString(4);
        DBUtil.close(rs, pst);    
    	startTime =MyUtil.getAddZero(OA2HRConstant.getWorkTime(leaveBean.getStartTime(), pk_corp, accountID));
		endTime = MyUtil.getAddZero(OA2HRConstant.getWorkTime(leaveBean.getEndTime(), pk_corp, accountID));
	log.info("销假"+startTime+endTime);
/*       this.leaveBean.setStartTime(OA2HRConstant.getWorkTime(
          this.leaveBean.getStartTime(), pk_corp, accountID));
        this.leaveBean.setEndTime(OA2HRConstant.getWorkTime(
          this.leaveBean.getEndTime(), pk_corp, accountID));*/
		this.leaveBean.setStartTime(startTime);
		   this.leaveBean.setEndTime(endTime);
        if ((pk_tbm_psndoc != null) && (!"".equals(pk_tbm_psndoc)))
        {
          pst = 
            conn.prepareStatement("select b.leavebeginday, b.leavebegintime, b.leaveendday, b.leaveendtime, b.leavenote, b.pk_leave_b from tbm_leaveb b left join bd_psndoc p on b.psncode = p.pk_psndoc where p.psncode=? and ( b.leavebeginday = ? and b.leavebegintime = ? or b.leaveendday = ? and b.leaveendtime = ? ) and ( b.dr is null or b.dr = '0')");
          pst.setString(1, this.leaveBean.getMemberCode());
          pst.setString(2, this.leaveBean.getStartDate());
          pst.setString(3, this.leaveBean.getStartTime());
          pst.setString(4, this.leaveBean.getEndDate());
          pst.setString(5, this.leaveBean.getEndTime());
          rs = pst.executeQuery();

        
          if (rs.next())
          {
        	
            String leavebeginday = rs.getString(1);
            String leavebegintime = rs.getString(2);
            String leaveendday = rs.getString(3);
            String leaveendtime = rs.getString(4);
           
            this.leaveBean.setReason("(销假:" + 
              this.leaveBean.getFormNumber() + 
              ")原因：" + this.leaveBean.getReason() + 
              "；原请假单：" + rs.getString(5));
            
            String pk_leave_b = rs.getString(6);
            
            DBUtil.close(rs, pst);
            if (setLeaveDay(leavebeginday, leavebegintime, leaveendday, leaveendtime))
            {
              float leaveDays = 0.0F;
              if ((!this.leaveBean.getStartDate().equals(this.leaveBean.getEndDate())) || 
              
                (!this.leaveBean.getStartTime().equals(this.leaveBean.getEndTime())))
              {
                pst = 
                  conn.prepareStatement("select calendar from tbm_psncalendar where pk_psndoc=? and calendar between ? and ? and if_rest='N' and (dr='0' or dr is null) order by calendar asc");
                pst.setString(1, pk_psndoc);
                pst.setString(2, this.leaveBean.getStartDate());
                pst.setString(3, this.leaveBean.getEndDate());
                
                rs = pst.executeQuery();
                while (rs.next())
                {
                  if (this.workDayArray == null) {
                    this.workDayArray = new ArrayList();
                  }
                  this.workDayArray.add(rs.getString(1));
                }
                DBUtil.close(rs, pst);
                

                pst = conn
                  .prepareStatement("select rq from tbm_fzqxjb where rq between ? and ? and pk_corp=? and (dr='0' or dr is null) order by rq asc");
                pst.setString(1, this.leaveBean.getStartDate());
                pst.setString(2, this.leaveBean.getEndDate());
                pst.setString(3, pk_corp);
                
                rs = pst.executeQuery();
                while (rs.next())
                {
                  if (this.holidayArray == null) {
                    this.holidayArray = new ArrayList();
                  }
                  this.holidayArray.add(rs.getString(1));
                }
                DBUtil.close(rs, pst);
                
                leaveDays = calculateLeaveDays();
                
                this.workDayArray = null;
                this.holidayArray = null;
              }
              pst = conn.prepareStatement("update tbm_leaveb b set b.leavebeginday = ?, b.leavebegintime = ?, b.leaveendday = ?, b.leaveendtime = ?, b.leavesumhour = ?, b.leavenote = ? where b.pk_leave_b = ?");



              pst.setString(1, this.leaveBean.getStartDate());
              pst.setString(2, this.leaveBean.getStartTime());
              pst.setString(3, this.leaveBean.getEndDate());
              pst.setString(4, this.leaveBean.getEndTime());
              pst.setString(5, String.valueOf(leaveDays));
              pst.setString(6, this.leaveBean.getReason());
              pst.setString(7, pk_leave_b);
              
              pst.execute();
              success = true;
            }
            else
            {
              this.errorMsg = "销假日期含有请假条未申请的请假日期";
            }
          }
          else
          {
            this.errorMsg = "HR系统中不存在需要销假的请假条，或者要销假时间为假期的中间段";
          }
        }
        else
        {
          this.errorMsg = 
            ("OA的请假类别无法和HR的请假类别匹配，OA请假类别为：" + this.leaveBean.getLeaveType());
        }
      }
      else
      {
        this.errorMsg = "请假人在HR系统中无考勤档案";
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
      log.error("《请假条》写入失败，表单summaryId:" + this.leaveBean.getSummaryId() + 
        "，单据编号为：" + this.leaveBean.getFormNumber(), e);
      this.errorMsg = "写入HR数据库异常";
      DBUtil.rollback(conn);
    }
    finally
    {
      DBUtil.setAutoCommit(conn, true);
      DBUtil.close(rs, pst, conn);
    }
    this.leaveBean = null;
    if (this.workDayArray != null) {
      this.workDayArray.clear();
    }
    this.workDayArray = null;
    if (this.holidayArray != null) {
      this.holidayArray.clear();
    }
    this.holidayArray = null;
    return success;
  }
  
  private boolean setLeaveDay(String leavebeginday, String leavebegintime, String leaveendday, String leaveendtime)
  {
    boolean right = false;
    if ((leavebeginday.equals(this.leaveBean.getStartDate())) && 
      (leavebegintime.equals(this.leaveBean.getStartTime())) && 
      (leaveendday.equals(this.leaveBean.getEndDate())) && 
      (leaveendtime.equals(this.leaveBean.getEndTime())))
    {
      this.leaveBean.setEndDate(leavebeginday);
      this.leaveBean.setEndTime(leavebegintime);
      right = true;
    }
    else if ((leavebeginday.equals(this.leaveBean.getStartDate())) && 
      (leavebegintime.equals(this.leaveBean.getStartTime())))
    {
      if (MyUtil.later(leaveendday, leaveendtime, this.leaveBean.getEndDate(), this.leaveBean.getEndTime()))
      {
        if (OA2HRConstant.END_WORK_TIME[0].equals(this.leaveBean.getEndTime()))
        {
          this.leaveBean.setStartDate(this.leaveBean.getEndDate());
          this.leaveBean.setStartTime(OA2HRConstant.START_WORK_TIME[1]);
          right = true;
        }
        else if (OA2HRConstant.END_WORK_TIME[1].equals(this.leaveBean.getEndTime()))
        {
          this.leaveBean.setStartTime(OA2HRConstant.START_WORK_TIME[0]);
          this.leaveBean.setStartDate(MyUtil.tomorrow(this.leaveBean
            .getEndDate()));
          right = true;
        }
        this.leaveBean.setEndDate(leaveendday);
        this.leaveBean.setEndTime(leaveendtime);
      }
    }
    else if ((leaveendday.equals(this.leaveBean.getEndDate())) && 
      (leaveendtime.equals(this.leaveBean.getEndTime())))
    {
      if (!MyUtil.later(leavebeginday, leavebegintime, this.leaveBean.getStartDate(), this.leaveBean.getStartTime()))
      {
        if (OA2HRConstant.START_WORK_TIME[1].equals(this.leaveBean.getStartTime()))
        {
          this.leaveBean.setEndDate(this.leaveBean.getStartDate());
          this.leaveBean.setEndTime(OA2HRConstant.END_WORK_TIME[0]);
          right = true;
        }
        else if (OA2HRConstant.START_WORK_TIME[0].equals(this.leaveBean.getStartTime()))
        {
          this.leaveBean.setEndTime(OA2HRConstant.END_WORK_TIME[1]);
          this.leaveBean.setEndDate(MyUtil.yesterday(this.leaveBean
            .getStartDate()));
          right = true;
        }
        this.leaveBean.setStartDate(leavebeginday);
        this.leaveBean.setStartTime(leavebegintime);
      }
    }
    return right;
  }
  private float calculateLeaveDays()
  {
    if (this.workDayArray == null) {
      return 0.0F;
    }
    float count = 0.0F;
    boolean isHoliday = false;
    int i = 0;
    for (int workDayArraySize = this.workDayArray.size(); i < workDayArraySize; i++)
    {
      String workDay = (String)this.workDayArray.get(i);
      isHoliday = false;
      if (this.holidayArray != null)
      {
        int j = 0;
        for (int holidayArraySize = this.holidayArray.size(); j < holidayArraySize; j++)
        {
          String holiday = (String)this.holidayArray.get(j);
          if (workDay.equals(holiday))
          {
            isHoliday = true;
            break;
          }
        }
      }
      if (!isHoliday) {
        if (workDay.equals(this.leaveBean.getStartDate()))
        {
          if (workDay.equals(this.leaveBean.getEndDate()))
          {
            if (this.leaveBean.getStartTime().equals(OA2HRConstant.START_WORK_TIME[0]))
            {
              if (this.leaveBean.getEndTime().equals(OA2HRConstant.END_WORK_TIME[0])) {
                count = 0.5F;
              } else if (this.leaveBean.getEndTime().equals(OA2HRConstant.END_WORK_TIME[1])) {
                count = 1.0F;
              }
            }
            else if (this.leaveBean.getStartTime().equals(OA2HRConstant.START_WORK_TIME[1])) {
              if (this.leaveBean.getEndTime().equals(OA2HRConstant.END_WORK_TIME[0])) {
                count = 0.0F;
              } else if (this.leaveBean.getEndTime().equals(OA2HRConstant.END_WORK_TIME[1])) {
                count = 0.5F;
              }
            }
          }
          else if (this.leaveBean.getStartTime().equals(OA2HRConstant.START_WORK_TIME[0])) {
            count += 1.0F;
          } else {
            count += 0.5F;
          }
        }
        else if (workDay.equals(this.leaveBean.getEndDate()))
        {
          if (this.leaveBean.getEndTime().equals(OA2HRConstant.END_WORK_TIME[1])) {
            count += 1.0F;
          } else {
            count += 0.5F;
          }
        }
        else {
          count += 1.0F;
        }
      }
    }
    return count;
  }

}
